import {
  addUserChannelApi,
  getAllChannelApi,
  getUserChannelApi,
} from '@/api/channel';
import { setChannel, hasToken } from '@/utils/storage';
import store, { AppDispatch } from '..';

import { getChannel } from './../../utils/storage';
import { delUserChannelApi } from './../../api/channel';
import { AddChannelType, ChannelType } from '../reducer/channel';

//获取用户频道
export const getUserChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      //有token，获取用户频道，存redux
      const res = await getUserChannelApi();
      dispatch({ type: 'chennel/userChannel', payload: res.data.channels }); //存redux
    } else {
      //没有token,且有本地时，调用本地存redux，否则调用所有频道接口
      const localChannel = getChannel();
      if (localChannel.length) {
        dispatch({ type: 'chennel/userChannel', payload: localChannel });
      } else {
        const res = await getAllChannelApi();
        //只存前10个
        const tenChannels = res.data.channels.slice(0, 10);
        setChannel(tenChannels); //存本地
        dispatch({ type: 'chennel/userChannel', payload: tenChannels }); //存redux
      }
    }
  };
};
//获取所有频道
export const getAllchannelAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannelApi();
    dispatch({ type: 'chennel/allChannel', payload: res.data.channels }); //所有频道
  };
};

//用户删除频道
export const delUserChannelAction = (data: ChannelType) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      await delUserChannelApi(data.id); //无返回值
    } else {
      const { userChannelList } = store.getState().channel;
      setChannel(userChannelList.filter((item) => item.id !== data.id));
    }
    dispatch({ type: 'channel/delUserChannel', payload: data });
  };
};
//用户添加频道
export const addUserChannelAction = (data: AddChannelType) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      await addUserChannelApi(data);
    } else {
      const { userChannelList } = store.getState().channel;
      setChannel([...userChannelList, data.channels[0]]);
    }
    dispatch({ type: 'channel/addUserChannel', payload: data.channels[0] });
  };
};
